package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.Base;
import com.isunland.managesystem.base.BaseFragment;
import com.isunland.managesystem.base.BaseVolleyActivity;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.BookOrderInfo;
import com.isunland.managesystem.entity.CurrentUser;
import com.isunland.managesystem.entity.LeaseMainList;
import com.isunland.managesystem.entity.LeaseMainListDetailOriginal;
import com.isunland.managesystem.entity.PayAndBackParams;
import com.isunland.managesystem.utils.MyDateUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.ToastUtil;
import java.util.HashMap;
import java.util.UUID;
import org.json.JSONException;

/**
 * 对象功能:
 * 开发公司: 北京信普达系统工程有限公司
 * 开发人员: wangyanan
 * 创建时间: 2017/1/4 19:24
 */

public class LeaseOrderDetailFragment extends BaseFragment {
  private static final String EXTRA_ITEM =
      LeaseOrderDetailFragment.class.getSimpleName() + ".EXTRA_ITEM";
  private static final int REQUEST_ALTER = 1;
  private static final int TYPE_SUBMIT = 2;
  private static final int TYPE_CANCEL = 3;
  private static final int TYPE_REMINDER = 4;
  private static final int REQUEST_PAY = 5;
  private static final int TYPE_DELETE = 6;
  @BindView(R.id.tv_orderNo) EditText tvOrderNo;
  @BindView(R.id.tv_leaseOrganizationColon) EditText tvLeaseOrganizationColon;
  @BindView(R.id.tv_leasePersonColon) EditText tvLeasePersonColon;
  @BindView(R.id.tv_customerAccountColon) TextView tvCustomerAccountColon;
  @BindView(R.id.tv_identityCardColon) EditText tvIdentityCardColon;
  @BindView(R.id.tv_contacts) EditText tvContacts;
  @BindView(R.id.tv_contactPhone) EditText tvContactPhone;
  @SuppressWarnings("all") @BindView(R.id.tv_leaseEquipmentDetail) TextView tvLeaseEquipmentDetail;
  @SuppressWarnings("all") @BindView(R.id.tv_actualHandleDetail) TextView tvActualHandleDetail;
  @BindView(R.id.tv_leaseIntroductionColon) TextView tvLeaseIntroductionColon;
  @BindView(R.id.tv_hasPayedDepositColon) EditText tvHasPayedDepositColon;
  @BindView(R.id.tv_hasPayedLeaseColon) EditText tvHasPayedLeaseColon;
  @BindView(R.id.tv_totalDepositColon) EditText tvTotalDepositColon;
  @BindView(R.id.tv_totalLeaseColon) EditText tvTotalLeaseColon;
  @BindView(R.id.tv_register) EditText tvRegister;
  @BindView(R.id.tv_registerTime) EditText tvRegisterTime;
  @BindView(R.id.tv_billStatus) EditText tvBillStatus;
  @BindView(R.id.tv_customerAccountNo) TextView tvCustomerAccountNo;
  @BindView(R.id.tv_leaseDate) TextView tvLeaseDate;

  private String mId;
  private LeaseMainList mItem;
  private BaseVolleyActivity mActivity;
  //private String mStatus;

  public static LeaseOrderDetailFragment newInstance(LeaseMainList item) {
    Bundle bundle = new Bundle();
    bundle.putSerializable(EXTRA_ITEM, item);
    LeaseOrderDetailFragment fragment = new LeaseOrderDetailFragment();
    fragment.setArguments(bundle);
    return fragment;
  }

  //初始化数据
  @Override public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);
    mActivity = ((BaseVolleyActivity) getActivity());
    mItem = (LeaseMainList) getArguments().getSerializable(EXTRA_ITEM);
    if (mItem != null) {
      mId = mItem.getId();
    }
  }

  //初始化界面
  @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
      @Nullable Bundle savedInstanceState) {

    View v = inflater.inflate(R.layout.fragment_lease_order_detail, container, false);
    ButterKnife.bind(this, v);
    return v;
  }

  //联网请求.
  @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    setTitleCustom(R.string.orderDetail);
    bindData(mItem);
    volleyPostInit(mId);
  }

  protected void volleyPostInit(String id) {
    if (TextUtils.isEmpty(id)) return;
    String mId = mItem.getId();

    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_LEASE_DETAIL);
    HashMap<String, String> params = new HashMap<>();
    params.put("id", mId);

    MyUtils.showDialogLoading(mActivity);
    mActivity.volleyPost(url, params, new VolleyResponse() {
      @Override public void onVolleyError(VolleyError arg0) {
        ToastUtil.show("获取详情失败!");
      }

      @Override public void onVolleyResponse(String json) throws JSONException {
        //json = MyUtils.readAssetsFile(MyApplication.getAppContext(), "testOperationDetail.json");
        LeaseMainListDetailOriginal original =
            new Gson().fromJson(json, LeaseMainListDetailOriginal.class);
        if (original.getResult() == Base.SUCCESS && original.getData() != null) {
          //mItem = original.getData();
          bindData(original.getData());
        } else {
          ToastUtil.show("获取详情失败!");
        }
      }
    });
  }

  private void bindData(LeaseMainList data) {
    if (data == null) return;
    tvOrderNo.setText(data.getLeaseNo());
    tvLeaseOrganizationColon.setText(data.getLeaseOrgName());

    tvLeasePersonColon.setText(data.getLeaseStaffName());
    tvCustomerAccountColon.setText(data.getCustomerAccount());
    tvCustomerAccountNo.setText(data.getCustomerAccountNo());
    //noinspection deprecation
    tvLeaseDate.setText(MyDateUtil.parseDateToString(MyDateUtil.stringToDate(data.getLeaseDate())));
    tvIdentityCardColon.setText(data.getIdCard());
    tvContacts.setText(data.getLinkman());
    tvContactPhone.setText(data.getLinkmanPhone());
    tvLeaseIntroductionColon.setText(data.getLeaseText());
    tvHasPayedDepositColon.setText(String.valueOf(data.getPayedDeposit()));
    tvHasPayedLeaseColon.setText(String.valueOf(data.getPayedLeaseMoney()));
    tvTotalDepositColon.setText(String.valueOf(data.getTotalPayDeposit()));
    tvTotalLeaseColon.setText(String.valueOf(data.getTotalPayLeaseMoney()));

    tvRegister.setText(data.getRegStaffName());
    tvRegisterTime.setText(data.getRegDate());
    tvBillStatus.setText(data.getDataStatusName());
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    super.onCreateOptionsMenu(menu, inflater);
    if (mItem == null || mItem.getDataStatus() == null) {
      return;
    }
    String mStatus = mItem.getDataStatus();
    if (mStatus.equals(BookOrderInfo.STATUS_NEW) || mStatus.equals(BookOrderInfo.STATUS_NEWBACK)) {
      inflater.inflate(R.menu.menu_delete_commit_alter, menu);
    }
    if (mStatus.equals(BookOrderInfo.STATUS_SUBMIT)) {
      inflater.inflate(R.menu.menu_cancel_order, menu);
    }
    if (mStatus.equals(BookOrderInfo.STATUS_CANCEL)) {
      inflater.inflate(R.menu.menu_delete, menu);
    }
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case R.id.menu_item_alter:
        LeaseOrderUpdateActivity.newInstance(this, mActivity, mItem, REQUEST_ALTER);
        break;
      case R.id.menu_item_submit:
        //volleypostUpdateStatus(mId,TYPE_SUBMIT);
        String totalDeposit = tvTotalDepositColon.getText().toString().trim();
        String totalLease = tvTotalLeaseColon.getText().toString().trim();
        //noinspection deprecation
        double deposit = MyUtils.valueOfDouble(totalDeposit, 0);
        //noinspection deprecation
        double lease = MyUtils.valueOfDouble(totalLease, 0);
        //如果金额小于等于0,直接提交.
        if (!((deposit + lease) > 0)) {
          volleypostUpdateStatus(mId, TYPE_SUBMIT);
        } else {
          pay(deposit, lease);
        }
        break;
      case R.id.menu_item_delete:
        volleypostUpdateStatus(mId, TYPE_DELETE);
        break;
      case R.id.menu_item_cancel:
        volleypostUpdateStatus(mId, TYPE_CANCEL);
        break;
      //case R.id.menu_item_reminder:
      //    volleypostUpdateStatus(mId,TYPE_REMINDER);
      //    break;
      default:
        break;
    }

    return super.onOptionsItemSelected(item);
  }

  private void pay(double deposit, double lease) {
    if (!((deposit + lease) > 0)) return;
    String id = "";
    String payMuch = "";
    String moneyType = "";
    if (deposit > 0) {
      id += UUID.randomUUID().toString();
      payMuch += String.valueOf(deposit);
      moneyType += PayAndBackParams.MONEY_TYPE_ANTECEDENT_FEE;
    }
    if (lease > 0) {
      id += getString(R.string.comma) + UUID.randomUUID().toString();
      payMuch += getString(R.string.comma) + String.valueOf(lease);
      moneyType += getString(R.string.comma) + PayAndBackParams.MONEY_TYPE_LEASE_FEE;
    }

    PayAndBackParams params = new PayAndBackParams();
    params.setId(id);
    params.setMainId(mId);
    params.setPayMuch(payMuch);
    params.setEditable(false);
    params.setMoneyType(moneyType);
    params.setBookOrderNo(mItem != null ? mItem.getOrderNo() : "");
    params.setOrderType(PayAndBackParams.ORDER_TYPE_LEASE);
    PayAndBackActivity.newInstance(this, PayAndBackActivity.class, params, REQUEST_PAY);
  }

  private void volleypostUpdateStatus(String id, int type) {
    if (TextUtils.isEmpty(id)) return;
    String status = null;
    switch (type) {
      case TYPE_SUBMIT:
        status = "submit";
        break;
      case TYPE_CANCEL:
        status = "backOrder";
        break;
      case TYPE_DELETE:
        status = "delete";
        break;
      case TYPE_REMINDER:
        //status="delete";
        break;
      default:
        break;
    }
    if (TextUtils.isEmpty(status)) return;

    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_LEASE_CHANGESTATUS);
    HashMap<String, String> params = new HashMap<>();
    params.put("ids", id);
    params.put("memberCode", CurrentUser.newInstance(mActivity).getMemberCode());
    params.put("dataStatus", status);

    mActivity.volleyPost(url, params, new VolleyResponse() {
      @Override public void onVolleyError(VolleyError arg0) {
        ToastUtil.show(R.string.failure_operation);
      }

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        Base original = new Gson().fromJson(arg0, Base.class);
        if (original != null && original.getResult() == Base.SUCCESS) {
          ToastUtil.show(R.string.updateOrderStatusSuccess);
          mActivity.setResult(Activity.RESULT_OK);
          mActivity.finish();
        } else {
          ToastUtil.show(getString(R.string.updateOrderStatusFail));
        }
      }
    });
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_OK) return;
    switch (requestCode) {
      case REQUEST_ALTER:
        //volleyPostInit();
        mActivity.setResult(Activity.RESULT_OK);
        mActivity.finish();
        break;
      case REQUEST_PAY:
        //volleyPostInit();
        //mActivity.setResult(Activity.RESULT_OK);
        //mActivity.finish();
        volleypostUpdateStatus(mId, TYPE_SUBMIT);
        break;
      default:
        break;
    }
    super.onActivityResult(requestCode, resultCode, data);
  }

  @OnClick({ R.id.tv_leaseEquipmentDetail, R.id.tv_actualHandleDetail })
  public void onClick(View view) {
    if (view == null) return;
    switch (view.getId()) {
      case R.id.tv_leaseEquipmentDetail:
        LeaseEquipmentListActivity.newInstance(this, mActivity, mId, mItem.getDataStatus(), 0,
            false);
        break;
      case R.id.tv_actualHandleDetail:
        LeaseActualListActivity.newInstance(this, mActivity, mId, 0);
        break;
      default:
        break;
    }
  }
}
